package com.test.fundible.fundible_00_analytics.FundibleUtil

import android.app.Application
import com.android.installreferrer.api.InstallReferrerClient
import com.android.installreferrer.api.InstallReferrerStateListener
import com.test.fundible.fundible_00_analytics.fundiblebean.PamfundibleGooglefundibleInstall
import com.test.fundible.fundible_00_analytics.fundiblehttp.FundibleHttpHelper
import com.test.fundible.fundible_00_analytics.fundibletimezone.FundibleTimeZoneUtil
import com.test.fundible.fundible_01_launcher.Base_fundibleApplication
import com.test.fundible.fundible_00_path.Paths_fundible
import com.test.fundible.fundible_00_utils.FundibleUtil
import java.sql.DriverManager.println

object FundibleGoogleInstallUtil {

    /**
     * google play 返回的install referrer，
     * 建议每个接口都需要带上这个字段
     */
    private var mInstallReferrer_fundible: String = ""

    /** 句柄 */
    private var mInstallReferrerClient_fundible: InstallReferrerClient =
        InstallReferrerClient.newBuilder(Base_fundibleApplication.getInstant()).build()

    /**
     * 初始化google install referref模块
     *
     * @param context Application
     */
    fun init_fundible(context: Application) {
        init_fundible(context) { saveS2sInfo_fundible(mutableListOf(FundibleUtil.getCommonPath_fundible())) }
    }

    /**
     * 初始化google install referref模块
     *
     * @param context Application
     * @param success 成功回调
     */
    fun init_fundible(context: Application, success: (String) -> Unit) {
        try {
            if (mInstallReferrer_fundible.isBlank()) {
                mInstallReferrerClient_fundible.startConnection(object :
                    InstallReferrerStateListener {
                    override fun onInstallReferrerSetupFinished(responseCode: Int) {
                        when (responseCode) {
                            InstallReferrerClient.InstallReferrerResponse.OK -> {
                                try {
                                    println("google install call back")
                                    val response = mInstallReferrerClient_fundible.installReferrer
                                    mInstallReferrer_fundible = response?.installReferrer ?: ""
                                    mInstallReferrerClient_fundible.endConnection()

                                    //回调通知
                                    success.invoke(mInstallReferrer_fundible)

                                } catch (e: Exception) {
                                    e.printStackTrace()
                                    mInstallReferrerClient_fundible.endConnection()
                                }
                            }
                            InstallReferrerClient.InstallReferrerResponse.FEATURE_NOT_SUPPORTED -> {

                                println("FEATURE_NOT_SUPPORTED")
                                mInstallReferrerClient_fundible.endConnection()
                            }
                            InstallReferrerClient.InstallReferrerResponse.SERVICE_UNAVAILABLE -> {

                                println("SERVICE_UNAVAILABLE")
                                mInstallReferrerClient_fundible.endConnection()
                            }
                        }
                    }

                    override fun onInstallReferrerServiceDisconnected() {
                    }
                })
            } else {
                //回调通知
                success.invoke(mInstallReferrer_fundible)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 获取Install Referrer
     */
    fun getInstallReferrer_fundible(): String {
        return mInstallReferrer_fundible
    }

    /**
     * 保存google s2s信息
     */
    fun saveS2sInfo_fundible(targetUrlList: List<String>) {
        val params =
            PamfundibleGooglefundibleInstall(
                channelCode = getInstallReferrer_fundible(),
                subChannelCode = getInstallReferrer_fundible()
            )
        val body = params.toEncryptParams(Paths_fundible.PATH_GP_INSTALL_TEMP)
//        val body = Gson().toJson(params).trim()
        val resultTargetUrlList = FundibleTimeZoneUtil.covertToRealTargetServers_fundible(targetUrlList)
        kotlin.io.println("====== $resultTargetUrlList")

        //传多国时，里触发多次
        resultTargetUrlList.forEach { path ->
//            val pathFormat =
//                if (path.endsWith(Url.PATH_GP_INSTALL_TEMP)) path else (path + Url.PATH_GP_INSTALL_TEMP)
            FundibleHttpHelper.postData_fundible(path, body)
        }
    }
}